//
//  ContactsViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/4.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ContactsViewController.h"
#import "KCContact.h"
#import "KCContactGroup.h"
#import "MsgCell.h"
#import "BusinessService+FJ.h"
#import "FriendDetailsMainVC.h"
#import "qryFriendVC.h"
@interface ContactsViewController ()<UITableViewDelegate,UITableViewDataSource,BaseTableDetelage,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *topView;//228
@property (weak, nonatomic) IBOutlet UITextField *suosouField;
@property (weak, nonatomic) IBOutlet UILabel *guanzhu;
@property (weak, nonatomic) IBOutlet BaseTable *table;
@property (weak, nonatomic) IBOutlet UILabel *fensi;

@property (weak, nonatomic) IBOutlet UILabel *qunzu;

@property (weak, nonatomic) IBOutlet UIView *gdView;
@property (weak, nonatomic) IBOutlet UIView *gdBgView;

@end

@implementation ContactsViewController{
    UITableView *_tableView;
    UIView *topview;
    NSMutableArray *data;
    NSMutableArray *redata;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    topview = _topView;
    data = [[NSMutableArray alloc]init];
    _suosouField.layer.cornerRadius = 13;
    redata = [[NSMutableArray alloc]init];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 5)];
    _suosouField.leftView = view;
    _suosouField.leftViewMode = UITextFieldViewModeAlways;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn addTarget:self action:@selector(qryAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"fwss1"] forState:UIControlStateNormal];
    _suosouField.rightView = btn;
    _suosouField.rightViewMode = UITextFieldViewModeAlways;
    [SVProgressHUD showWithStatus:@"加载中..."];
    _table.bdelegate = self;
    [_table Refresh];
    
    //xhw2018-2-8加
    _gdBgView.layer.cornerRadius = 5;
    _gdBgView.clipsToBounds = YES;
}

//xhw2018-2-8加
- (void)moreMiss {
    _gdView.hidden = YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self qryAction:nil];
    return YES;
}


#pragma mark 查询
-(void)qryAction:(UIButton *)btn{
    [self.view endEditing:YES];
    NSMutableArray *rary = [[NSMutableArray alloc]init];
    if([_suosouField.text trim].length!=0){
        for (int i=0; i<_suosouField.text.length; i++) {
            NSRange range = NSMakeRange(i,1);
            NSString *subString = [_suosouField.text substringWithRange:range];
            const char *cString = [subString UTF8String];
            if (strlen(cString) == 3 )
            {
                NSMutableArray *ary = redata;
                for (int i=0; i<ary.count;i++) {
                    LoginResponseModel *model = [[LoginResponseModel alloc]init];
                    [model serializationWithDictionary:[ary objectAtIndex:i]];
                    if([model.nickname rangeOfString:_suosouField.text].location !=NSNotFound)//_roaldSearchText
                    {
                        [rary addObject:model];
                    }
                }
             }else if(strlen(cString)==1)
            {
                for (int i =0; i<redata.count; i++) {
                    LoginResponseModel *g = [[LoginResponseModel alloc]init];
                    [g serializationWithDictionary:[redata objectAtIndex:i]];
                    NSString *n = [ValidateHelper firstCharactor:g.nickname];
                    if ([n isEqualToString:_suosouField.text.uppercaseString]) {
                        [rary addObject:g];
                    }
                }
             }
        }
    }
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    qryFriendVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"qryFriendVC"];
    searchResultDetailController.ary = rary;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    //xhw2018-2-8加
    _gdView.hidden = YES;
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreMiss)];
    tapGes.cancelsTouchesInView = NO;
    tapGes.numberOfTapsRequired = 1;
    [_table addGestureRecognizer:tapGes];
    
    [_table Refresh];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    _gdView.hidden = YES;
}

-(void)initData:(int)index{
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
    [[BusinessService shareInstance]friendlist:dic success:^(id result) {
        [SVProgressHUD dismiss];
        data = [_table result:result olddata:data index:index];
        LoginResponseModel *model = [data firstObject];
        _guanzhu.text = [NSString stringWithFormat:@"%@位",model.follownum];
        _fensi.text = [NSString stringWithFormat:@"%@位",model.fansnum];
        _qunzu.text = [NSString stringWithFormat:@"%@个",model.groupnums];
        redata = model.friendlist;
        NSMutableArray *sdtal = [[NSMutableArray alloc]init];
        for (NSMutableDictionary *user in model.friendlist) {
            if ([[user objectForKey:@"uid"] intValue] == [[AppDelegate shareDelegate].user.uid intValue]) {
                continue;
            }
            [sdtal addObject:user];
        }
         data =  [ValidateHelper dataFrom:sdtal];
        [_table reloadData];
    } failure:^(id result) {[SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:result];
    }];
}



#pragma mark - 数据源方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSLog(@"计算分组数");
    return data.count;
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    KCContactGroup *group1=data[section];
    return group1.contacts.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 228;
    }
    return 30;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        topview = _topView;
        return topview;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KCContactGroup *group= data[indexPath.section];
    LoginResponseModel *contact = group.contacts[indexPath.row];
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
    cell.img.clipsToBounds = YES;
    //xhw2018-1-18改
//    cell.name.text = contact.nickname;
    if (contact.remarkname.length != 0) {
        cell.name.text = contact.remarkname;
    }
    else {
        cell.name.text = contact.nickname;
    }
    
    [ValidateHelper setImage:contact.headsmall img:cell.img istoux:YES];
    cell.content.text = contact.sign;
    cell.job.text =  [NSString stringWithFormat:@"%@岁",[ValidateHelper timeToAge:contact.age] ];
    //xhw2018-1-19改bug15259
    NSString * logintime  = [ValidateHelper timeStringWith:contact.logintime.doubleValue multiLine:NO];
    NSString *distance = [ValidateHelper DistanceFormat:contact.distance];
    cell.distanceLabel.text = [NSString stringWithFormat:@"%@|%@",distance,logintime];
    
    return cell;
}

#pragma mark 返回每组头标题名称
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if(section != 0){
        KCContactGroup *group=data[section];
        return group.name;
    }
    return nil;
}

#pragma mark 返回每组标题索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *indexs=[[NSMutableArray alloc]init];
    for(KCContactGroup *group in data){
        [indexs addObject:group.name];
    }
    return indexs;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DTModel *model =[[DTModel alloc]init];
    KCContactGroup *group= data[indexPath.section];
    LoginResponseModel *contact = group.contacts[indexPath.row];
    model.uid = contact.uid;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    FriendDetailsMainVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FriendDetailsMainVC"];
    searchResultDetailController.model = model;
    if (contact.remarkname.length != 0) {
        searchResultDetailController.remarkName = contact.remarkname;
    }
    else {
        
    }
    
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
- (IBAction)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma 添加好友、关注、粉丝、群主 界面
- (IBAction)nextAction:(UIButton *)sender {
    if ([[sender.titleLabel.text trim] isEqualToString:@"添加好友"]) {
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFriendsVC"];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }
    if ([[sender.titleLabel.text trim] isEqualToString:@"关注"]) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FollowListVC"];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
    }
    if ([[sender.titleLabel.text trim] isEqualToString:@"粉丝"]) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FansListVC"];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
    }
    if ([[sender.titleLabel.text trim] isEqualToString:@"群组"]) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupListVC"];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }
    
}

- (IBAction)moreAction:(UIBarButtonItem *)sender {
    _gdView.hidden = NO;
}
- (IBAction)addAction:(id)sender {
    _gdView.hidden = YES; //xhw2018-1-10加
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFriendsVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}

- (IBAction)faqihuihuanAction:(UIButton *)sender {
    _gdView.hidden = YES; //xhw2018-1-10加
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"NewConversationVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
- (IBAction)sysAction:(UIButton *)sender {
    
    _gdView.hidden = YES; //xhw2018-1-10加
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"QRCodeVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
- (IBAction)huivewAction:(id)sender {
    
    _gdView.hidden = YES;
    //    NSLog(@"%@",[[ThinkChat instance]getLatestNotify]);
    NSArray<TCSession *> *sec = (NSMutableArray *)[TCSession getSessionListTimeLine];
    for (TCSession * session in sec) {
        [[ThinkChat instance] hasReadSessionID:session.ID typeChat:forChatTypeUser];
        [[ThinkChat instance] hasReadSessionID:session.ID typeChat:forChatTypeRoom];
        [[ThinkChat instance] hasReadSessionID:session.ID typeChat:forChatTypeGroup];
        
    }

    NSArray<TCNotify *> *notyArr = [TCNotify getNotifyListTimeLineWithFinalNotify:nil];
    
    for (TCNotify *not in notyArr) {
        [TCNotify hasReadNotify:not];
    }
}


@end
